package com.nowcoder.interceptor;

import com.nowcoder.entity.LoginRecord;
import com.nowcoder.entity.User;
import com.nowcoder.service.UserService;
import com.nowcoder.utils.CookieUtil;
import com.nowcoder.utils.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * @Author liujilong
 * @Project nowcoder
 * @File LoginTokenInterceptor
 * @Date 2021/12/28 1:45 下午
 **/
@Component
public class LoginTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Autowired
    private HostHolder hostHolder;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从cookie中获取token
        String token = CookieUtil.getValue(request, "token");
        if (token != null) {
            LoginRecord loginToken = userService.findLoginToken(token);
            //检查token是否有效
            if (loginToken != null && loginToken.getStatus() == 0
                    && loginToken.getExpirtion().after(new Date())) {
                //根据token查询用户
                User user = userService.findByUid(loginToken.getUid());
                hostHolder.setUser(user);
            }
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        User user = hostHolder.getUser();
        if (user != null && modelAndView != null) {
            modelAndView.addObject("loginUser", user);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        hostHolder.clear();
    }
}
